package com.metronoteapp.until;

import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.util.Log;

public class AudioRecorderUntil extends Activity {

	private String TAG = AudioRecorderUntil.class.getSimpleName();
	private static String path;
	private static String mFileName = null;
	private MediaRecorder mRecorder = null;
	private MediaPlayer mPlayer = null;

	public AudioRecorderUntil() {
		File direct = new File(Constants.PATH_AUDIO);
		Log.v(TAG, Constants.PATH_AUDIO);
		// Create folder
		if (!direct.exists()) {
			if (direct.mkdir()) {
				Log.v(TAG, "AudioRecorderUntil() | Created folder: "
						+ Constants.PATH_AUDIO);
			} else {
				Log.v(TAG,
						"AudioRecorderUntil() | Created Failed!"
								+ direct.getParent());
			}

		} else {
			Log.v(TAG, "AudioRecorderUntil() | Folder exist");
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (mRecorder != null) {
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
		}
		super.onPause();
	}

	/*
	 * Start playing an audio file
	 * */
	public void startPlaying(String fileName) {
		mFileName = fileName;
		mPlayer = new MediaPlayer();
		try {
			mPlayer.setDataSource(mFileName);
			mPlayer.prepare();
			mPlayer.start();
		} catch (IOException e) {
			Log.e(TAG, "prepare() failed");
		}
	}

	/*
	 * Stop playing an audio file
	 * */
	public void stopPlaying() {
		mPlayer.release();
		mPlayer = null;
	}

	/*
	 * Start record an audio file
	 * */
	public void startRecording(String fileName) {
		mFileName = Constants.PATH_AUDIO + "/" + fileName + ".wav";
		Log.v(TAG, "String Recording: " + mFileName);
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setOutputFile(mFileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
		} catch (IOException e) {
			Log.e(TAG, "prepare() failed");
		}

		mRecorder.start();
		Log.v(TAG, "Started!");
	}

	/*
	 * Stop record an audio file
	 * */
	public void stopRecording() {
		Log.v(TAG, "Stoping!");
		mRecorder.stop();
		Log.v(TAG, "Releasing!");
		mRecorder.release();
		mRecorder = null;
	}
}